﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Data.SqlClient;
using System.ServiceModel.Activation;
using System.Net;
using System.Net.Mail;
//using SendGridMail;
//using SendGridMail.Transport;

namespace AG.Apps.WebServices
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    // NOTE: In order to launch WCF Test Client for testing this service, please select Service1.svc or Service1.svc.cs at the Solution Explorer and start debugging.
    
    public class Key
    {
        public string Keyseries { get; set; }
        public string ProductionName { get; set; }
        public int Used { get; set; }
    }

    public class UserInfo
    {
        public int Id { get; set; }
        public string UserName { get; set; }
        public string UserEmail { get; set; }
        public string ProductKey { get; set; }
        public string ProductName { get; set; }
    }
    [AspNetCompatibilityRequirements(RequirementsMode=AspNetCompatibilityRequirementsMode.Allowed)]
    public class UserData : IUserData
    {
        //List<string> AvailableKey = new List<string>();
        List<Key> AvailableKeys;

        public void ProvideKeytoUser(string UserEmail, string ProductN)
        {
            
            AvailableKeys= new List<Key>();
            Key NewKey = new Key() { Keyseries = KeyGenerator.GetSerialKeyAlphaNumaric() ,ProductionName="SharePoint Permission Explorer",Used=1};
            using (SqlConnection connection = new SqlConnection(GetConnectionString()))
            {
                using (SqlCommand command = connection.CreateCommand())
                {
                    connection.Open();
                    command.CommandText="select* from ProductKey";
                    using (SqlDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            AvailableKeys.Add(new Key()
                            {
                                Keyseries = reader["Key"] as string,
                                ProductionName = reader["ProductionName"] as string,
                                Used = Convert.ToInt32( reader["Used"]),
                            });
                        }
                    }
                }
            }
            while (checkAvailableKey(NewKey.Keyseries))
            {
                NewKey.Keyseries = KeyGenerator.GetSerialKeyAlphaNumaric();
            }

            using (SqlConnection connection = new SqlConnection(GetConnectionString()))
            {
                connection.Open();
                try
                {
                    using (SqlCommand command = new SqlCommand("INSERT INTO ProductKey VALUES(@Key,@ProductionName,@Used)", connection))
                    {
                        command.Parameters.Add(new SqlParameter("Key", NewKey.Keyseries));
                        command.Parameters.Add(new SqlParameter("ProductionName", NewKey.ProductionName));
                        command.Parameters.Add(new SqlParameter("Used", NewKey.Used));
                        command.ExecuteNonQuery();
                    }
                }
                catch
                {
                }
            }//TODO: send new key to user via email
  //          EmailSender.SendMail(UserEmail, NewKey.Keyseries);
            //retrieve available keys of the product in database
            //check if the new key is available in database or not
            //If not, Add new Key in Database
            //Send ProductKey to User
        }

        public bool ValidateKey(string ProductKey, string ProductN)
        {
            //check if the ProductKey exist in database
            AvailableKeys = new List<Key>();
            using (SqlConnection connection = new SqlConnection(GetConnectionString()))
            {
                using (SqlCommand command = connection.CreateCommand())
                {
                    connection.Open();
                    command.CommandText = "select* from ProductKey";
                    using (SqlDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            AvailableKeys.Add(new Key()
                            {
                                Keyseries = reader["Key"] as string,
                                ProductionName = reader["ProductionName"] as string,
                                Used = Convert.ToInt32(reader["Used"]),
                            });
                        }
                    }
                }
            }

            return checkValidateKey(ProductKey,ProductN);
        }

        public ValidationResult AddUser(string UserN, string UserEmail, string ProductN, string ProductKey)
        {
            //add User to database
            if (ValidateKey(ProductKey, ProductN))
            {
                using (SqlConnection connection = new SqlConnection(GetConnectionString()))
                {
                    connection.Open();
                    try
                    {
                        using (SqlCommand command = new SqlCommand("INSERT INTO UserInfo VALUES(@UserName,@UserEmail,@ProductKey,@ProductName)", connection))
                        {
                            command.Parameters.Add(new SqlParameter("UserName", UserN));
                            command.Parameters.Add(new SqlParameter("UserEmail", UserEmail));
                            command.Parameters.Add(new SqlParameter("ProductKey", ProductKey));
                            command.Parameters.Add(new SqlParameter("ProductName", ProductN));
                            command.ExecuteNonQuery();
                        }
                        return new ValidationResult(){Validate=true,Name=""};
                    }
                    catch(Exception ex)
                    {
                        return new ValidationResult() { Validate = false, Name = "" };
                    }
                }
            }
            else
                return new ValidationResult() { Validate = false, Name = "" };
        }
        public void TestKey()
        {
            Key NewKey = new Key() { Keyseries = KeyGenerator.GetSerialKeyAlphaNumaric(), ProductionName = "SharePoint Permission Explorer", Used = 1 };
            using (SqlConnection connection = new SqlConnection(GetConnectionString()))
            {
                connection.Open();
                try
                {
                    using (SqlCommand command = new SqlCommand("INSERT INTO ProductKey VALUES(@Key,@ProductionName,@Used)", connection))
                    {
                        command.Parameters.Add(new SqlParameter("Key", NewKey.Keyseries));
                        command.Parameters.Add(new SqlParameter("ProductionName", NewKey.ProductionName));
                        command.Parameters.Add(new SqlParameter("Used", NewKey.Used));
                        command.ExecuteNonQuery();
                    }
                }
                catch
                {
                }
            }
        }

        public bool ValidateKeyCrossDomain(string ProductN, string ProductKey,string Callback)
        {
            //check if the ProductKey exist in database

            return true;
        }
        public string GetConnectionString()
        {
            return System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        }
        public bool checkAvailableKey(string CurrentKey)
        {
            foreach (Key num in AvailableKeys)
            {
                if (CurrentKey == num.Keyseries)
                {
                    return true;
                }
            }
            return false;
        }
        public bool checkValidateKey(string CurrentKey, string CurrentProN)
        {
            foreach (Key num in AvailableKeys)
            {
                if (CurrentKey == num.Keyseries&& CurrentProN==num.ProductionName&&num.Used==1)
                {
                    return true;
                }
            }
            return false;
        }
    }
}
